Ext.onReady(function(){
    Ext.QuickTips.init();
    /**
     * ----------------------------------------------------
     *                 north
     *-----------------------------------------------------
     *   project     | setgrid| project      | schedule bar
     *               |        |              | ------------
     *               |        | setdetail    | breakgridpanel
     *  billingreport|       | breaklist    |
     *  ____________________________________________________
     *                    south
     * ------------------------------------------------------
     *
     *
     */
    /*
     * Breaklist
     * shows the detailed break test results
     */
    var breakliststore = new Ext.data.JsonStore({
    
        root: 'results',
        totalProperty: 'totalCount',
        idProperty: 'id',
        remoteSort: true,
        fields: [{
            name: 'col_name',
            type: 'string'
        }, 'weight', 'days', 'hold', 'break_type', 'mold_type', 'break_psi', 'col_name', 'tech', 'project_num', 'required_psi', {
            name: 'broken_date',
            type: 'date'
        }, {
            name: 'break_date',
            type: 'date'
        }],
        
        proxy: new Ext.data.HttpProxy({
            url: '/breakschedule/getschedule'
        })
    });
    
    
    var breaklistpanel = new Ext.grid.GridPanel({
        store: breakliststore,
        loadMask: true,
        split: true,
        hidden: true,
        frame: false,
        viewConfig: {
            forceFit: true
        },
        width: 400,
        height: 200,
        autoScroll: true,
        animCollapse: false,
        title: 'Break List',
        viewConfig: {
            forceFit: true,
            getRowClass: function(r, rowIndex, p, store){
            
                //render the break tests ouside the select period disabled
                var dt;
                if (r.data.broken_date == null) {
                    dt = r.data.break_date
                }
                else {
                    dt = r.data.broken_date
                };
                
                if (dt <= end_dt.getValue() && dt >= start_dt.getValue()) {
                    return 'enabled-row'
                }
                else {
                    return 'disabled-row'
                };
                            }
        },
        columns: [{
            id: 'Col_name',
            header: "Col",
            width: 10,
            sortable: true,
            dataIndex: 'col_name',
            hidden: false
        }, {
            header: "Days",
            width: 10,
            sortable: true,
            dataIndex: 'days',
            hidden: false,
            renderer: function(v, p, r){
                //Mark a break as Hold if days = 0
                if (v == 0) {
                    return 'H'
                }
                else {
                    return v
                }
            }
            
        }, {
            header: "Sched'd",
            width: 15,
            sortable: true,
            dataIndex: 'break_date',
            renderer: Ext.util.Format.dateRenderer('m/d/Y'),
            hidden: true
        }, {
            header: "Broken",
            width: 20,
            sortable: true,
            dataIndex: 'broken_date',
            renderer: function(v, p, r){
                //if broken use broken_date, otherwise use break_date
                var dt;
                if (r.data.broken_date == null) {
                    dt = r.data.break_date
                }
                else {
                    dt = v
                };
                
                if (r.data.days == 0) {
                    return '--'
                }
                else {
                    return Ext.util.Format.dateRenderer('m/d/Y')(dt)
                }
                
                
                
                
            },
            hidden: false
        }, {
            header: "Strength",
            width: 15,
            sortable: true,
            dataIndex: 'break_psi',
            hidden: false,
            renderer: function(v, p, r){
                //check if the test passed
                if (parseFloat(r.data.required_psi) > parseFloat(v)) {
                    return '<span style="color:red">' + v + '</span>'
                }
                else {
                    return '<span style="color:green">' + v + '</span>'
                }
            }
            
        }, {
            header: "Required",
            width: 15,
            sortable: true,
            dataIndex: 'required_psi',
            hidden: false
        
        }, {
            header: "Weight",
            width: 15,
            sortable: true,
            dataIndex: 'weight',
            hidden: false
        
        }, {
            header: "Break By",
            width: 20,
            sortable: true,
            dataIndex: 'tech',
            hidden: false
        
        }]
    
    });
    
    
    /*
     * breakgrid
     * This is the schedule panel on the right, list all the tests
     */
    var breakstore = new Ext.data.GroupingStore({
        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'totalCount',
            idProperty: 'id',
            remoteSort: true,
            fields: [{
                name: 'client_id',
                type: 'string'
            }, {
                name: 'project_num',
                type: 'string'
            }, {
                name: 'set_num',
                type: 'string'
            }, {
                name: 'mold_type',
                type: 'string'
            }, {
                name: 'col_name',
                type: 'string'
            }, {
                name: 'break_date',
                type: 'date'
            }, {
                name: 'hold_flag',
                type: 'string'
            }, {
                name: 'id',
                type: 'string'
            }, {
                name: 'groupfld',
                type: 'string'
            }, 'required_psi', 'break_psi', 'status']
        }),
        proxy: new Ext.data.HttpProxy({
            //            url: '/breakschedule/getschedule'
            url: '/breakschedule/getbreaklist2'
        }),
        sortInfo: {
            field: 'break_date',
            direction: "ASC"
        },
        groupField: 'groupfld',
        groupOnSort: false,
        remoteGroup: true
    });
    
    var calendar = new Ext.DatePicker({
        cls: 'calendar-css'
    
    });
    
    var breakgridpanel = new Ext.grid.GridPanel({
        store: breakstore,
        loadMask: true,
        hideHeaders: false,
        
        columns: [{
            id: 'id',
            header: "id",
            width: 60,
            sortable: true,
            dataIndex: 'id',
            hidden: true
        }, {
            header: "group",
            width: 20,
            sortable: true,
            dataIndex: 'groupfld',
            hidden: true
        }, {
        
            header: 'No.',
            dataIndex: 'id',
            width: 150,
            renderer: function(value, p, r){
                //the label for each break sample is prj-set-col
                return String.format('{0}-{1}-{2}', r.data.project_num, r.data.set_num, String.fromCharCode(65 + parseInt(r.data.col_name)))
                
            }
        }, {
            header: 'PSI Req',
            dataIndex: 'required_psi',
            width: 50
        }, {
            header: 'PSI Brk',
            dataIndex: 'break_psi',
            width: 50,
            renderer: function(value, p, r){
                //check if it is a hold sample
                if (value == '') {
                    if (r.data.hold_flag == 'H') {
                        return 'HOLD'
                    }
                    else {
                        return 'N/T'
                    }
                    
                }
                //check the test result
                if (r.data.break_psi < r.data.required_psi) {
                    return '<span style="color:red;">' + value + '</span>';
                }
                else {
                    return '<span style="color:green;">' + value + '</span>';
                }
            }
        }],
        
        view: new Ext.grid.GroupingView({
            forceFit: true,
            groupTextTpl: '{gvalue} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
        }),
        
        frame: false,
        width: 250,
        height: 450,
        autoHeight: true,
        collapsible: true,
        animCollapse: false,
        
        header: false,
        hideGroupedColumn: true
    });
    
    
    /*
     * projectpanel
     * This is the tree showing all the project by client
     */
    var tpl = new Ext.Template('<h2 class="title">{text}</h2>');
    tpl.compile();
    
    var td = new Date();
    
    var y, m, d;
    y = td.getFullYear();
    m = td.getMonth();
    d = td.getDate();
    
    projectpanel = new Ext.tree.TreePanel({
        id: 'project-panel',
        title: 'Projects',
        //        region: 'center',
        split: true,
        height: 300,
        minSize: 150,
        autoScroll: true,
        //		frame: true,
        
        //        tbar: new Ext.Toolbar({
        //            items: [{
        //                text: 'Between: ',
        //                xtype: 'label'
        //            }, {
        //                xtype: 'datefield',
        //                width: 80,
        //                id: 'project-start-dt'
        //            }, {
        //                xtype: 'label',
        //                text: ' and '
        //            }, {
        //                xtype: 'datefield',
        //                width: 80,
        //                id: 'project-end-dt'
        //            }, {
        //                xtype: 'button',
        //                text: 'Filter',
        //                id: 'project-filter-button'
        //            }]
        //        }),
        
        // tree-specific configs:
        rootVisible: false,
        lines: false,
        singleExpand: true,
        useArrows: true,
        
        loader: new Ext.tree.TreeLoader({
            dataUrl: '/projects',
            baseParams: { //    action: 'projecttree'
}
        }),
        root: {
            nodeType: 'async',
            draggable: false,
            text: 'Projects',
            //this id is used to load the tree automatically
            id: 'root'
        }
    });
    
    /*
     * The data behind the project detail
     */
    var projectstore = new Ext.data.JsonStore({
    
        root: 'results',
        totalProperty: 'totalCount',
        idProperty: 'id',
        remoteSort: true,
        fields: ["cyl_hold_ct", "beam_hold_cost", "cube_ct", "cube_hold_ct", "cube_cost", "cube_price", "hold_price", "total", "no_days", "day_price", "cyl_cost", "beam_price", "cube_hold_cost", "client_name", "cyl_ct", "beam_hold_ct", "cyl_price", "project_name", "set_ct", "grand", "cyl_hold_cost", "days_cost", "set_price", "project_num", "beam_ct", "start_dt", "end_dt", "beam_cost"],
        
        proxy: new Ext.data.HttpProxy({
            //            url: '/project/getproject'
            url: '/project/projectcost'
        })
    });
    /*
     * new invoice window
     */
    var invoice_project_store = new Ext.data.JsonStore({
        proxy: new Ext.data.HttpProxy({
            url: '/invoices?node=list_project'
        })
    });
    var invoice_client_store = new Ext.data.JsonStore({
        proxy: new Ext.data.HttpProxy({
            url: '/invoices?node=list_client'
        })
    });
    
    var invoice_client_combo = new Ext.form.ComboBox({
        store: invoice_client_store,
        displayField: 'client_name',
        typeAhead: false,
        mode: 'remote',
        triggerAction: 'all',
        emptyText: 'Select a client...',
        selectOnFocus: true,
        fieldLabel: 'Client',
        name: 'client_name'
    });
    
    invoice_client_combo.on('select', function(combo, record){
        var client_name = invoice_client_combo.getValue();
        invoice_project_store.setBaseParam('client_name', client_name);
        invoice_project_store.load();
    })
    
    var invoice_project_combo = new Ext.form.ComboBox({
        store: invoice_project_store,
        displayField: 'project_name',
        name: 'project_name',
        typeAhead: false,
        mode: 'remote',
        triggerAction: 'all',
        emptyText: 'Select a project...',
        selectOnFocus: true,
        fieldLabel: 'Project'
    });
    invoice_project_combo.on('select', function(combo, record){
    
        invoice_job_number.setValue(record.get('project_number'))
    });
    
    var invoice_job_number = new Ext.form.TextField({
        fieldLabel: 'Job Number'
    });
    
    var new_invoice_form = new Ext.FormPanel({
        labelWidth: 75,
        url: '/invoices?node=insert',
        frame: true,
        width: 350,
        defaults: {
            width: 230
        },
        defaultType: 'textfield',
        items: [new Ext.form.DateField({
            fieldLabel: 'Invoice Date',
            name: 'invoice_date',
            id: 'dt-invoice-date'
        }), new Ext.form.DateField({
            fieldLabel: 'From',
            name: 'invoice_from',
            id: 'dt-invoice-from'
        }), new Ext.form.DateField({
            fieldLabel: 'To',
            name: 'invoice_to',
            id: 'dt-invoice-to'
        }), invoice_client_combo, invoice_project_combo, invoice_job_number, {
            xtype: 'radiogroup',
            columns: 2,
            fieldLabel: 'Testing Type',
            items: [{
            
                boxLabel: 'Compaction',
                name: 'testing_type',
                inputValue: 'compaction'
            }, {
                boxLabel: 'Asphalt',
                name: 'testing_type',
                inputValue: 'asphalt'
            }]
        }],
        buttons: [{
            text: 'Save',
            handler: function(){
                if (new_invoice_form.getForm().isValid()) {
                    new_invoice_form.getForm().submit({
                        url: '/invoices?node=insert',
                        waitMsg: 'Creating new invoice...',
                        success: function(fp, o){
                            Ext.MessageBox.alert('Status', 'New Invoice Created');
							new_invoice_form.getForm().reset();
							new_invoice_window.hide();
							invoice_panel.getLoader().load(invoice_panel.getRootNode())
                        }
                    });
                }
            }
        }, {
            text: 'Close',
            handler: function(){
				new_invoice_form.getForm().reset();
                new_invoice_window.hide()
            }
        }]
    
    });
    var new_invoice_window = new Ext.Window({
        modal: true,
        id: 'new-invoice-window',
        layout: 'fit',
        width: 500,
        height: 300,
        closeAction: 'hide',
        plain: true,
        title: 'New Invoice',
        items: [new_invoice_form]
    });
    
    /*
     * invoice store
     */
    var invoice_panel = new Ext.tree.TreePanel({
        id: 'invoice-panel',
        title: 'Invoices',
        split: true,
        height: 300,
        minSize: 150,
        autoScroll: true,
        
        tbar: new Ext.Toolbar({
            items: [            //			{
            //                text: 'Between: ',
            //                xtype: 'label'
            //            }, {
            //                xtype: 'datefield',
            //                width: 80,
            //                id: 'project-start-dt'
            //            }, {
            //                xtype: 'label',
            //                text: ' and '
            //            }, {
            //                xtype: 'datefield',
            //                width: 80,
            //                id: 'project-end-dt'
            //            },
            {
                xtype: 'button',
                text: 'New Invoice',
                id: 'button-new-invoice',
                handler: function(){
                    new_invoice_window.show()
                }
				
            }, {
					xtype: 'button',
					text: 'Delete Invoice',
					handler: function(){
						alert('not working yet')
					}
				}]
        }),
        
        // tree-specific configs:
        rootVisible: false,
        lines: false,
        singleExpand: true,
        useArrows: true,
        
        loader: new Ext.tree.TreeLoader({
            dataUrl: '/invoices',
            baseParams: { //    action: 'projecttree'
}
        }),
        root: {
            nodeType: 'async',
            draggable: false,
            text: 'Invoices',
            //this id is used to load the tree automatically
            id: 'root'
        }
    });
    
    /*
     * data behind the setdetail
     */
    setdetailstore = new Ext.data.JsonStore({
    
        root: 'results',
        totalProperty: 'totalCount',
        idProperty: 'id',
        remoteSort: true,
        fields: [{
            name: 'id',
            type: 'string'
        }, {
            name: 'project_num',
            type: 'string'
        }, {
            name: 'set_num',
            type: 'string'
        }, {
            name: 'date_poured',
            type: 'date'
        }, {
            name: 'pour_loc',
            type: 'string'
        }, {
            name: 'date_received',
            type: 'date'
        }, 'air', 'slump', 'made_by'],
        
        proxy: new Ext.data.HttpProxy({
            url: '/setinfo/getset'
        })
    });
    
    
    /*
     * testgrid
     * This list all the tests for selected project or break
     */
    var teststore = new Ext.data.JsonStore({
        proxy: new Ext.data.HttpProxy({
            url: '/testings'
        })
    });
    
    var LIMIT = 25;
    var testgridpanel = new Ext.grid.GridPanel({
        store: teststore,
        loadMask: true,
        id: 'testgrid-panel',
        split: true,
        columns: [],
        listener: {
            viewready: function(g){
                g.getSelectionModel().selectFirstRow()
            }
        },
        viewConfig: {
            forceFit: false
        },
        // paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            pageSize: LIMIT,
            store: teststore,
            displayInfo: true,
            displayMsg: 'Displaying topics {0} - {1} of {2}',
            emptyMsg: "No topics to display"
        }),
        frame: false,
        //        width: 600,
        height: 600,
        autoScroll: true,
        //        collapsible: true,
        
        animCollapse: false,
        region: 'west',
        title: 'Testing List'
    });
    
    
    
    
    /*
     * center panel
     */
    contentPanel = {
        id: 'center-panel',
        region: 'center', // this is what makes this panel into a region within the containing layout
        layout: 'anchor',
        margins: '0 0 0 0',
        title: 'Testing Detail',
        autoScroll: true,
        border: true,
        items: [{
        
            id: 'project-detail-panel',
            border: false,
            autoScroll: true
        
        }, {
            id: 'detail-panel',
            border: false
        }, {
            id: 'break-list-panel',
            border: false
        }, breaklistpanel, {
            id: 'break-detail-panel'
        }]
    };
    
    /*
     * billreport panel
     * generate the bill for select time period
     */
    var billreport = {
        title: 'Invoices',
        xtype: 'form',
        bodyStyle: 'padding:5px 5px 0',
        defaults: {
            width: 100
        },
        items: [{
            xtype: 'button',
            text: 'Create New Invoice'
        }, {
            xtype: 'datefield',
            fieldLabel: 'Start',
            id: 'billing-start'
        }, {
            xtype: 'datefield',
            fieldLabel: 'End',
            id: 'billing-end'
        }, {
            xtype: 'button',
            text: 'Generate Billing Report',
            handler: function(){
                var start_dt = Ext.getCmp('billing-start');
                var end_dt = Ext.getCmp('billing-end');
                if ((typeof start_dt.getValue() == 'string') || (typeof end_dt.getValue() == 'string')) {
                    Ext.MessageBox.alert('Error', 'Date entered not valid.');
                    return
                    
                }
                
                if (end_dt.getValue() < start_dt.getValue()) {
                    Ext.MessageBox.alert('Error', 'End date is earlier than start date');
                    return
                }
                
                
                window.open('/project/monthlycost?' +
                Ext.urlEncode({
                    start: Ext.util.Format.dateRenderer('m/d/Y')(start_dt.getValue()),
                    end: Ext.util.Format.dateRenderer('m/d/Y')(end_dt.getValue())
                }))
            }
        }]
    };
    
    
    /*
     * west panel
     */
    var westpanel = {
        layout: 'accordion',
        id: 'west-panel',
        title: 'DLZ FIELD TESTING DATABASE',
        region: 'west',
        border: true,
        
        collapsible: true,
        split: true,
        margins: '2 0 5 5',
        width: 275,
        minSize: 100,
        maxSize: 500,
        items: [projectpanel, invoice_panel]
    };
    
    /*
     * viewport
     */
    var viewport = new Ext.Viewport({
        layout: 'border',
        items: [new Ext.BoxComponent({ // raw element
            region: 'north',
            el: 'header',
            height: 25
            //			bodyStyle: 'padding:5px 5px 15px 5px'
        }), //west
 westpanel, //center
        {
        
            region: 'center', // this is what makes this panel into a region within the containing layout
            layout: 'border',
            margins: '2 2 2 0',
            
            border: false,
            items: [testgridpanel, contentPanel]
        }, new Ext.BoxComponent({ // raw element
            region: 'south',
            el: 'footer',
            height: 16
        }), {
            region: 'east',
            layout: 'anchor',
            collapsible: true,
            collapsed: true,
            title: 'Schedule Bar',
            autoScroll: true,
            width: 250,
            tbar: new Ext.Toolbar({
            
            
                items: calendar
            }),
            
            items: [breakgridpanel]
        }]
    });
    
    
    
    /*
     * UI logic
     */
    /*
     * Filter projects using time range
     */
    //called when the filter button is clicked.
    function filterProject(){
        var start_dt = Ext.getCmp('project-start-dt');
        var end_dt = Ext.getCmp('project-end-dt');
        var qMsg = String.format('From {0} to {1}', Ext.util.Format.dateRenderer('m/d/Y')(start_dt.getValue()), Ext.util.Format.dateRenderer('m/d/Y')(end_dt.getValue()))
        //		Ext.getCmp('query-panel').body.update(qMsg);
        Ext.getCmp('center-panel').setTitle(qMsg);
        
        if ((typeof start_dt.getValue() == 'string') || (typeof end_dt.getValue() == 'string')) {
            Ext.MessageBox.alert('Error', 'Date entered not valid.');
            return
            
        }
        
        if (end_dt.getValue() < start_dt.getValue()) {
            Ext.MessageBox.alert('Error', 'End date is earlier than start date');
            return
        }
        var f = Ext.util.Format.dateRenderer('m/d/Y')(start_dt.getValue());
        var t = Ext.util.Format.dateRenderer('m/d/Y')(end_dt.getValue());
        var rt = projectpanel.getRootNode();
        rt.setId('all-' + f + '-' + t);
        projectpanel.getLoader().load(rt);
        tpl = new Ext.Template('');
        var cmp = Ext.getCmp('detail-panel');
        tpl.overwrite(cmp.body, []);
        cmp = Ext.getCmp('project-detail-panel');
        tpl.overwrite(cmp.body, []);
        
        //clear the list of sets
        
        setstore.removeAll();
        
        breaklistpanel.setVisible(false);
        
    }
    
    
    
    
    
    /*
     * schedule bar calendar
     * when a date is selected, dislay schedule ONE week from the date selected
     */
    calendar.on('select', function(dp, d){
        breakstore.setBaseParam('today', d.format('m/d/Y'));
        breakstore.load()
    });
    
    
    
    /*
     * when a set is selected in the setgrid panel
     */
    testgridpanel.getSelectionModel().on('rowselect', function(sm, rowIdx, r){
    
        //        setdetailstore.setBaseParam('project', r.data.project_num);
        //        setdetailstore.setBaseParam('set', r.data.set_num);
        //        setdetailstore.load();
        var html = '<table border="0.5" style="font-size: 10px">';
        for (var name in r.data) {
            html = html + '<tr><td>' + name + '</td><td>' + r.data[name] + '</td></tr>'
        };
        html = html + '</table>';
        Ext.getCmp('break-detail-panel').body.update(html);
        
        
        
    });
    
    /*
     * show the detail of a project
     */
    function renderProjectDetail(data){
        //		var tpl = new Ext.Template('<b>Project:</b> {project_name} ({project_num})<br/>', '<b>Client:</b> {client}<br/>', '<b>Contact:</b> {contact_name}', '<h1>Cost Information:</h1>', '<table class="dlz-billing">', '<tr><th>Cylinder<br>($/EA)</th><th>Beam<br>($/EA)</th><th>Cube<br>($/EA)</th><th>Hold<br>($/EA)</th><th>Set<br>($/EA)</th><th>Days</th></tr>', 
        //		'<tr style="color:green"><td>${cyl_price}</td><td>${beam_price}</td><td>${cube_price}</td><td>${hold_price}</td><td>{set_price}</td><td>N/A</td></tr>', '</table>', '<hr>');
        var tpl = new Ext.Template('<table class="dlz-billing">', '<tr><th colspan="3" class="dlz-heading2" style="background:#ffffff;">From: <span class="dlz-bold">{start_dt}</span> to  <span class="dlz-bold">{end_dt}</span></th><th colspan="2">Cylinder</th><th colspan="2">Beam</th><th colspan="2">Cubes</th><th rowspan="2">No. of Days</th></tr>', '<tr><th>Client</th><th>Project Name</th><th>Project Number</th><th>Break</th><th>Hold</th><th>Break</th><th>Hold</th><th>Break</th><th>Hold</th></tr>', '<tr><td rowspan="2">{client_name}</td><td rowspan="2">{project_name}</td><td rowspan="1">{project_num}</td><td>{cyl_ct} </td><td>{cyl_hold_ct}</td><td>{beam_ct} </td><td>{beam_hold_ct}</td><td>{cube_ct} </td><td>{cube_hold_ct}</td><td rowspan="2">{no_days}</td></tr>', '<tr class="dlz-gray"><td>Unit Price ($ per test)</td><td>{cyl_price}</td><td>{hold_price}</td><td>{beam_price}</td><td>{hold_price}</td><td>{cube_price}</td><td>{hold_price}</td></tr>', '<tr><td class="dlz-right dlz-highlight" colspan="2">Total</td><td class="dlz-highlight dlz-left">{total}</td><td>{cyl_cost}</td><td>{cyl_hold_cost}</td><td>{beam_cost}</td><td>{beam_hold_cost}</td><td>{cube_cost}</td><td>{cube_hold_cost}</td><td>{days_cost}</td></tr>', '</table><hr>');
        var cmp = Ext.getCmp('project-detail-panel');
        cmp.body.hide();
        tpl.overwrite(cmp.body, data);
        cmp.body.slideIn('l', {
            stopFx: true,
            duration: .1
        });
    }
    
    /*
     * show the dtail of a project when the projet store is loaded
     */
    projectstore.on('load', function(ds){
        //overwrite something to show the details of the project
        var r = ds.getAt(0).data;
        renderProjectDetail(r)
        
    });
    
    /*
     * when the tree of project panel is clicked, show the setlist and update the project details
     */
    projectpanel.getSelectionModel().on('selectionchange', function(tree, node){
        if (node.attributes.leaf) {
            //list all the tests
            teststore.setBaseParam('tableid', node.id);
            teststore.load({
                params: {
                    limit: LIMIT,
                    start: 0
                }
            });
            testgridpanel.setTitle('Testing List -' + node.attributes.text);
        }
        
    });
    
    teststore.on('metachange', function(store, meta){
        //update the grid columns
        //update the columns
        var c;
        var config = [];
        var lookup = {};
        for (var i = 0, len = meta.fields.length; i < len; i++) {
            c = meta.fields[i];
            if (c.header !== undefined) {
                if (typeof c.dataIndex == "undefined") {
                    c.dataIndex = c.name;
                }
                if (typeof c.renderer == "string") {
                    c.renderer = Ext.util.Format[c.renderer];
                }
                if (typeof c.id == "undefined") {
                    c.id = 'c' + i;
                }
                if (c.editor && c.editor.isFormField) {
                    c.editor = new Ext.grid.GridEditor(c.editor);
                }
                c.sortable = true;
                c.width = 100;
                //delete c.name;
                config[config.length] = c;
                lookup[c.id] = c;
            }
        }
        testgridpanel.getColumnModel().config = config;
        testgridpanel.getColumnModel().lookup = lookup;
        testgridpanel.view.refresh(true)
        
    })
    
    /*
     * show set detail information
     */
    function renderSetDetail(data){
        var tpl = new Ext.XTemplate('<h1>Set Info</h1>', '<table class="dlz-billing">', '<tr><th>Date Poured</th><th>Set #</th><th>Air Content(%)</th><th>Slump(in)</th><th>Made by</th></tr>', '<tr><td>{date_poured}</td><td>{set_num}</td><td>{air}</td><td>{slump}</td><td>{made_by}</td></tr>', '<tr ><td>Location of Pour</td><td colspan="4"> {pour_loc}</td></tr>', '</table><hr>');
        var cmp = Ext.getCmp('detail-panel');
        data.date_received = Ext.util.Format.dateRenderer('m/d/Y')(data.date_received);
        data.date_poured = Ext.util.Format.dateRenderer('m/d/Y')(data.date_poured);
        cmp.body.hide();
        tpl.overwrite(cmp.body, data);
        cmp.body.slideIn('l', {
            stopFx: true,
            duration: .1
        });
        breaklistpanel.setVisible(true);
        
        
        breakliststore.setBaseParam('project', data.project_num);
        breakliststore.setBaseParam('set', data.set_num);
        breakliststore.load();
        
        
        //clear break detail
        Ext.getCmp('break-detail-panel').body.update('');
        
        
    };
    
    setdetailstore.on('load', function(ds){
        var r = ds.getAt(0).data;
        renderSetDetail(r)
    });
    
    
    /*
     * when the schedule list is clicked, update the project, set and breakgird information
     */
    breakgridpanel.getSelectionModel().on('rowselect', function(sm, rIdx, r){
        var start_dt = Ext.getCmp('project-start-dt');
        var end_dt = Ext.getCmp('project-end-dt');
        projectstore.setBaseParam('prj', r.data.project_num);
        projectstore.setBaseParam('start', Ext.util.Format.dateRenderer('m/d/Y')(start_dt.getValue()));
        projectstore.setBaseParam('end', Ext.util.Format.dateRenderer('m/d/Y')(end_dt.getValue()));
        projectstore.load();
        setdetailstore.setBaseParam('project', r.data.project_num);
        setdetailstore.setBaseParam('set', r.data.set_num);
        setdetailstore.load();
        //empty the setlist
        
        setstore.removeAll()
    });
    
    /*
     * when breaklist is clicked, show the detail for the break
     */
    breaklistpanel.getSelectionModel().on('rowselect', function(sm, rIdx, r){
        var tpl = new Ext.Template('Mold Type: {mold_type}<br>', 'Column: {col_name}<br>', 'Break Type: {break_type}<br>');
        tpl.overwrite(Ext.getCmp('break-detail-panel').body, r.data)
    })
    
    
    /*
     * Initialize UI
     */
    /*
     * Default time range A month from today
     */
    /*
     * default the schedule a week from today
     */
    calendar.setValue(new Date());
    //load the projects
    //filterProject();
    //load the schedule
    breakstore.setBaseParam('today', Ext.util.Format.dateRenderer('m/d/Y')(calendar.getValue()));
    breakstore.load();
    
    
});

